#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){
    ui->setupUi(this);

    connect(ui->btnCustomers, SIGNAL(clicked()), this, SLOT(showCustomersTable()));
    connect(ui->btnOrders, SIGNAL(clicked()), this, SLOT(showOrdersTable()));

    connect(ui->btnAddCustomer, SIGNAL(clicked()), &_customer, SLOT(show()));
    connect(ui->btnEditCustomer, SIGNAL(clicked()), this, SLOT(editCustomer()));
    connect(ui->tableViewCustomers, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(editCustomer()));
    connect(ui->btnDeleteCustomer, SIGNAL(clicked()), this, SLOT(deleteCustomer()));

    connect(ui->btnAddOrder, SIGNAL(clicked()), this, SLOT(addOrder()));
    connect(ui->btnEditOrder, SIGNAL(clicked()), this, SLOT(editOrder()));
    connect(ui->tableViewOrders, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(editOrder()));
    connect(ui->btnDeleteOrder, SIGNAL(clicked()), this, SLOT(deleteOrder()));

    connect(&_customer, SIGNAL(updateCostumer()), this, SLOT(loadCustomers()));
    connect(&_customer, SIGNAL(updateOrders()), this, SLOT(loadOrders()));
    connect(&_order, SIGNAL(updateOrders()), this, SLOT(loadOrders()));

    connect(ui->lineEditSearchCustomers, SIGNAL(textChanged(QString)), this, SLOT(filterCustomers()));
    connect(ui->lineEditSearchOrders, SIGNAL(textChanged(QString)), this, SLOT(filterOrders()));
    connect(ui->actionCreateBackup,SIGNAL(triggered()),this,SLOT(createBackup()));
    connect(ui->actionLoadBackup,SIGNAL(triggered()),this,SLOT(loadBackup()));

    centerOnScreen();
    _dbUser = "userHeggel";
    _dbUserPass = "userHeggel";
    _dbName = "heggel";
    loadDb();
}

void MainWindow::loadDb(){
    DBConnection::Instance()->disconnect();
    DBConnection::Instance()->connect("localhost", _dbName, _dbUser, _dbUserPass);

    _customersModel = new QSqlQueryModel();
    _ordersModel = new QSqlQueryModel();

    loadCustomers();
    loadOrders();
}

void MainWindow::loadBackup(){
    QString fileName = QFileDialog::getOpenFileName(this, tr("Cargar"),
                                QDir::homePath());
    if(fileName=="")
        return;
    int ret = QMessageBox::warning(this, tr("Backup"),
                                   tr("Se cargara en la base de datos el backup seleccionado.\n"
                                      "Esta seguro de cargarlo?"),
                                   QMessageBox::Yes,QMessageBox::No);
    if(ret==QMessageBox::Yes){
        _backupSystem.loadBackup(fileName, _dbName,_dbUser,_dbUserPass);
        loadDb();
    }

}

void MainWindow::createBackup(){
    QString fileName = QFileDialog::getSaveFileName(this, tr("Guardar"),
                                QDir::homePath());
    _backupSystem.makeBackup(fileName, _dbName,_dbUser,_dbUserPass);
}

void MainWindow::centerOnScreen(){

    QRect rect = this->frameGeometry();
    rect.moveCenter(QDesktopWidget().availableGeometry().center());
    this->move(rect.topLeft());
    qApp->processEvents();
}

void MainWindow::loadCustomers(){

    _customer.getCustomers(_customersModel);
    ui->tableViewCustomers->setModel(_customersModel);
    ui->tableViewCustomers->hideColumn(0);//id pedido
}

void MainWindow::loadOrders(){

    _order.getOrders(_ordersModel);
    ui->tableViewOrders->setModel(_ordersModel);
    ui->tableViewOrders->hideColumn(0);//id pedido
    ui->tableViewOrders->hideColumn(1);//id cliente
}

void MainWindow::showCustomersTable(){

    ui->stackedWidget->setCurrentIndex(0);
}

void MainWindow::showOrdersTable(){

    ui->stackedWidget->setCurrentIndex(1);
}

void MainWindow::editCustomer(){

    if (ui->tableViewCustomers->currentIndex().row() == -1){
        return;
    }

    _customer.setCustomer(ui->tableViewCustomers->model()->data(ui->tableViewCustomers->model()->index(ui->tableViewCustomers->currentIndex().row(), 0)).toString());
    _customer.show();
}

void MainWindow::deleteCustomer(){

    if (ui->tableViewCustomers->currentIndex().row() == -1){
        return;
    }

    int result = QMessageBox::question(this, "Eliminar cliente", "¿Está seguro que desea eliminar el cliente seleccionado?", QMessageBox::Yes, QMessageBox::No);

    if(result == QMessageBox::Yes){

        _customer.deleteCustomer(ui->tableViewCustomers->model()->data(ui->tableViewCustomers->model()->index(ui->tableViewCustomers->currentIndex().row(), 0)).toString());
        loadCustomers();
    }
}

void MainWindow::addOrder(){

    if (ui->tableViewCustomers->currentIndex().row() == -1){
        return;
    }

    QStringList customerData;
    customerData << ui->tableViewCustomers->model()->data(ui->tableViewCustomers->model()->index(ui->tableViewCustomers->currentIndex().row(), 0)).toString();
    customerData << ui->tableViewCustomers->model()->data(ui->tableViewCustomers->model()->index(ui->tableViewCustomers->currentIndex().row(), 1)).toString();
    customerData << ui->tableViewCustomers->model()->data(ui->tableViewCustomers->model()->index(ui->tableViewCustomers->currentIndex().row(), 2)).toString();
    customerData << ui->tableViewCustomers->model()->data(ui->tableViewCustomers->model()->index(ui->tableViewCustomers->currentIndex().row(), 3)).toString();
    customerData << ui->tableViewCustomers->model()->data(ui->tableViewCustomers->model()->index(ui->tableViewCustomers->currentIndex().row(), 4)).toString();
    customerData << ui->tableViewCustomers->model()->data(ui->tableViewCustomers->model()->index(ui->tableViewCustomers->currentIndex().row(), 5)).toString();
    customerData << ui->tableViewCustomers->model()->data(ui->tableViewCustomers->model()->index(ui->tableViewCustomers->currentIndex().row(), 6)).toString();
    customerData << ui->tableViewCustomers->model()->data(ui->tableViewCustomers->model()->index(ui->tableViewCustomers->currentIndex().row(), 7)).toString();
    customerData << ui->tableViewCustomers->model()->data(ui->tableViewCustomers->model()->index(ui->tableViewCustomers->currentIndex().row(), 8)).toString();

    _order.setCustomer(customerData);
    _order.show();
}

void MainWindow::editOrder(){

    if (ui->tableViewOrders->currentIndex().row() == -1){
        return;
    }

    _order.setOrder(ui->tableViewOrders->model()->data(ui->tableViewOrders->model()->index(ui->tableViewOrders->currentIndex().row(), 0)).toString());
    _order.show();
}

void MainWindow::deleteOrder(){

    if (ui->tableViewOrders->currentIndex().row() == -1){
        return;
    }

    int result = QMessageBox::question(this, "Eliminar pedido", "¿Está seguro que desea eliminar el pedido seleccionado?", QMessageBox::Yes, QMessageBox::No);

    if(result == QMessageBox::Yes){

        _order.deleteOrder(ui->tableViewOrders->model()->data(ui->tableViewOrders->model()->index(ui->tableViewOrders->currentIndex().row(), 0)).toString());
        loadOrders();
    }
}

void MainWindow::filterCustomers(){

    filter(ui->tableViewCustomers, _customersModel, ui->cmbSearchByCustomers->currentText(), ui->lineEditSearchCustomers->text());
}

void MainWindow::filterOrders(){

    filter(ui->tableViewOrders, _ordersModel, ui->cmbSearchByOrders->currentText(), ui->lineEditSearchOrders->text());
}

void MainWindow::filter(QTableView* &table, QSqlQueryModel* model, QString column, QString value){

    QString text = value.toLower();
    for(int i=0; i<model->rowCount(); i++){
        table->showRow(i);
        if(!model->record(i).value(column).toString().toLower().startsWith(text))
            table->hideRow(i);
    }
}


MainWindow::~MainWindow(){
    delete ui;
}
